package com.shuma.auth.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.shuma.auth.entity.PRODUCTSTATE;
import com.shuma.auth.entity.RestBean;
import com.shuma.auth.entity.dto.Account;
import com.shuma.auth.mapper.*;
import com.shuma.auth.model.dto.*;
import com.shuma.auth.model.po.*;
import com.shuma.auth.service.ProductBaseService;
import com.shuma.auth.service.UserProductService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.List;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author lele
 */
@Slf4j
@Service
public class ProductBaseServiceImpl extends ServiceImpl<ProductBaseMapper, ProductBase> implements ProductBaseService {

    @Autowired
    UserProductService userProductService;
    @Resource
    UserProductMapper userProductMapper;

    @Resource
    ProductBaseMapper productBaseMapper;

    @Resource
    SupplierMapper supplierMapper;
    @Resource
    ProductMarketMapper productMarketMapper;

    @Resource
    OperateRecordMapper operateRecordMapper;

    @Resource
    AccountMapper accountMapper;

    /**
     * 只查这个用户管理或代理的商品，管理员可看所有商品
     * @param pageParams
     * @param queryProductParamsDto
     * @param userId
     * @return
     */
    @Override
    public Page<ProductDto> pageProduct(PageParams pageParams, QueryProductParamsDto queryProductParamsDto, Long userId) {
        //用户信息
        Account user = accountMapper.selectById(userId);
        //构造分页参数
        Integer pageSize = pageParams.getPageSize();
        Integer pageNo = pageParams.getPageNo();
        Integer pageStart = (pageNo - 1) * pageSize;
        Integer pageEnd = pageStart + pageSize;
        //无模糊查询参数
        if (queryProductParamsDto == null) {
            queryProductParamsDto = new QueryProductParamsDto();
        }
        //用户是普通运营
        if (user.getRoleId() == 2) {
            queryProductParamsDto.setUserId(userId);
        } else if (user.getRoleId() == 1) {
            //管理员
            queryProductParamsDto.setIsAdmin(1);
        }
        //设置分页条件
        queryProductParamsDto.setPageStart(pageStart);
        queryProductParamsDto.setPageEnd(pageEnd);
        //查商品数据
        List<ProductDto> list = productBaseMapper.selectProductDto(queryProductParamsDto);
        //查询的总记录数
        Long count  = productBaseMapper.selectProductCount(queryProductParamsDto);
        //构造返回结果
        Page<ProductDto> page = new Page<>();
        page.setRecords(list);
        page.setSize(pageSize);
        page.setCurrent(pageNo);
        page.setTotal(count);
        //返回结果
        return page;

    }

    //查询用户信息
    public Account selectUserById(Long userId) {
        return accountMapper.selectById(userId);
    }

    /**
     * 暂存商品
     * @param addProductDto
     * @param id
     * @return
     */
    @Override
    @Transactional
    public RestBean<String> tempSaveProduct(AddProductDto addProductDto, Long id) {
        //不用考虑商品名称的唯一
        if (addProductDto.getName() == null) {
            return RestBean.failure(0, "商品名称为空");
        }
        //提供商名称
        String supplierName = addProductDto.getSupplierName();
        //提供商手机号
        String supplierPhone = addProductDto.getSupplierPhone();
        Supplier supplier = new Supplier();
        if (supplierName != null || supplierPhone != null) {
            //保存供应商信息
            supplier.setName(supplierName);
            supplier.setPhone(supplierPhone);
            supplierMapper.insert(supplier);
        }

        //保存商品信息
        ProductBase productBase = new ProductBase();
        BeanUtils.copyProperties(addProductDto, productBase);
        //设置商品提供商id
        if (supplierName != null || supplierPhone != null) {
            productBase.setSupplierId(supplier.getId());
        }
        //设置为创建状态
        productBase.setState(PRODUCTSTATE.SAVE);
        //加入DB
        productBaseMapper.insert(productBase);
        //商品id
        Long productId = productBase.getId();

        //保存营销信息
        List<ProductMarket> productMarketList = addProductDto.getProductMarketList();
        if (productMarketList != null) {
            for (ProductMarket productMarket : productMarketList) {
                productMarket.setProductId(productId);
                productMarketMapper.insert(productMarket);
            }
        }

        //保存创建人信息
        UserProduct createUserProduct = new UserProduct();
        //管理人
        createUserProduct.setLevel(0);
        createUserProduct.setProductId(productId);
        Account user = selectUserById(id);
        createUserProduct.setUsername(user.getUsername());
        createUserProduct.setUserId(id);
        userProductMapper.insert(createUserProduct);

        //保存代理人信息
        List<UserProduct> proxyUserInfoDtos = addProductDto.getProxyUserInfoDtos();
        if (proxyUserInfoDtos != null) {
            for (UserProduct proxyUserInfoDto : proxyUserInfoDtos) {
                UserProduct userProduct = new UserProduct();
                //代理人身份
                userProduct.setLevel(1);
                //代理人id
                userProduct.setUserId(proxyUserInfoDto.getUserId());
                //代理人名称
                userProduct.setUsername(proxyUserInfoDto.getUsername());
                //商品id
                userProduct.setProductId(productId);
                userProductMapper.insert(userProduct);
            }
        }

        //操作记录表
        saveOperateRecord(productId, PRODUCTSTATE.SAVE, id);

        return RestBean.success(productId.toString());
    }

    /**
     * 记录表
     * @param productId
     * @param state
     * @param userId
     */
    public void saveOperateRecord(Long productId, Integer state, Long userId) {

        OperateRecord operateRecord = new OperateRecord();
        operateRecord.setProductId(productId);
        operateRecord.setStatus(state);
        operateRecord.setUpdateTime(LocalDateTime.now());
        //改为实际的用户
        operateRecord.setUserId(userId);
        operateRecordMapper.insert(operateRecord);
    }

    @Override
    @Transactional
    public RestBean<String> foreverSaveProduct(AddProductDto addProductDto, Long id) {

        //保存供应商信息
        String supplierName = addProductDto.getSupplierName();
        String supplierPhone = addProductDto.getSupplierPhone();
        Supplier supplier =null;
        LambdaQueryWrapper<Supplier> supplierLambdaQueryWrapper = new LambdaQueryWrapper<>();
        if (supplierName != null && supplierPhone != null) {
            supplierLambdaQueryWrapper.eq(Supplier::getName, supplierName)
                    .eq(Supplier::getPhone, supplierPhone);
            supplier=supplierMapper.selectOne(supplierLambdaQueryWrapper);
        }

        //供应商数据新加
        if(supplier == null){
            supplier = new Supplier();
            supplier.setName(supplierName);
            supplier.setPhone(supplierPhone);
            supplierMapper.insert(supplier);
        }

        //保存商品信息
        ProductBase productBase = new ProductBase();
        BeanUtils.copyProperties(addProductDto, productBase);
        productBase.setSupplierId(supplier.getId());
        //创建
        productBase.setState(PRODUCTSTATE.SAVE);
        productBaseMapper.insert(productBase);
        Long productId = productBase.getId();

        //保存营销信息
        List<ProductMarket> productMarketList = addProductDto.getProductMarketList();
        for (ProductMarket productMarket : productMarketList) {
            productMarket.setProductId(productId);
            productMarketMapper.insert(productMarket);
        }
        //保存创建人信息
        UserProduct createUserProduct = new UserProduct();
        //管理人
        createUserProduct.setLevel(0);
        createUserProduct.setProductId(productId);
        Account user = selectUserById(id);
        createUserProduct.setUsername(user.getUsername());
        createUserProduct.setUserId(id);
        userProductMapper.insert(createUserProduct);

        //保存代理人信息
        List<UserProduct> proxyUserInfoDtos = addProductDto.getProxyUserInfoDtos();
        if(proxyUserInfoDtos!=null&&proxyUserInfoDtos.size()!=0){
            for (UserProduct proxyUserInfoDto : proxyUserInfoDtos) {
                UserProduct userProduct = new UserProduct();
                //代理人身份
                userProduct.setLevel(1);
                //代理人id
                userProduct.setUserId(proxyUserInfoDto.getUserId());
                //代理人名称
                userProduct.setUsername(proxyUserInfoDto.getUsername());
                //商品id
                userProduct.setProductId(productId);
                userProductMapper.insert(userProduct);
            }
        }


        //操作记录表
        saveOperateRecord(productId, PRODUCTSTATE.SAVE, id);

        return RestBean.success(productId.toString());
    }

    /**
     * 管理人和商品创建人可以查看商品所有信息，商品代理人看不到商品代理人信息
     * @param id
     * @param userId
     * @return
     */
    @Override
    public ProductInfoDto selectProductInfoById(Long id, Long userId) {
        ProductInfoDto productInfoDto = new ProductInfoDto();
        //设置商品基本信息
        ProductBase productBase = productBaseMapper.selectById(id);
        BeanUtils.copyProperties(productBase, productInfoDto);
        //设置提供商
        Long supplierId = productBase.getSupplierId();
        Supplier supplier = supplierMapper.selectById(supplierId);
        productInfoDto.setSupplierName(supplier.getName());
        productInfoDto.setSupplierPhone(supplier.getPhone());
        //设置营销信息
        LambdaQueryWrapper<ProductMarket> productMarketLambdaQueryWrapper = new LambdaQueryWrapper<>();
        productMarketLambdaQueryWrapper.eq(ProductMarket::getProductId, id);
        List<ProductMarket> productMarkets = productMarketMapper.selectList(productMarketLambdaQueryWrapper);
        productInfoDto.setProductMarketList(productMarkets);
        //判断用户是管理人还是代理人，代理人不可见代理人信息
        Integer isManager = userProductMapper.isManager(userId, id);
        Account user = selectUserById(userId);

        //管理人或管理员
        if ((isManager != null && isManager == 0) || user.getRoleId() == 1) {
            //根据商品id查代理人
            LambdaQueryWrapper<UserProduct> userProductLambdaQueryWrapper = new LambdaQueryWrapper<>();
            userProductLambdaQueryWrapper.eq(UserProduct::getLevel, 1)
                    .eq(UserProduct::getProductId, id);
            List<UserProduct> userProducts = userProductMapper.selectList(userProductLambdaQueryWrapper);
            //设置代理人信息
            productInfoDto.setProxyUserInfoDtos(userProducts);
        }
        return productInfoDto;
    }


    /**
     * 管理人和商品创建人可以编辑商品所有信息，代理人不可编辑代理人
     * @param editProductDto
     * @param userid
     * @return
     */
    @Override
    @Transactional
    public RestBean<Void> editProduct(ProductInfoDto editProductDto, Long userid) {

        //设置商品基本信息
        ProductBase productBase = new ProductBase();
        BeanUtils.copyProperties(editProductDto, productBase);
        //商品id
        Long productBaseId = productBase.getId();

        //1.更新提供商id
        Supplier supplier = null;
        //供应商名称
        String supplierName = editProductDto.getSupplierName();
        //供应商手机号
        String supplierPhone = editProductDto.getSupplierPhone();
        LambdaQueryWrapper<Supplier> supplierLambdaQueryWrapper = new LambdaQueryWrapper<>();
        if (supplierName == null || supplierPhone == null) {
            return RestBean.failure(0, "供应商数据为空");
        }
        supplierLambdaQueryWrapper.eq(Supplier::getName, supplierName)
                .eq(Supplier::getPhone, supplierPhone);
        supplier = supplierMapper.selectOne(supplierLambdaQueryWrapper);
        //供应商为空，插入新数据
        if (supplier == null) {
            supplier = new Supplier();
            supplier.setName(supplierName);
            supplier.setPhone(supplierPhone);
            supplierMapper.insert(supplier);
        }
        //设置供应商id
        productBase.setSupplierId(supplier.getId());
        //2.更新价格信息
        LambdaQueryWrapper<ProductMarket> productMarketLambdaQueryWrapper = new LambdaQueryWrapper<>();
        productMarketLambdaQueryWrapper.eq(ProductMarket::getProductId, productBaseId);
        productMarketMapper.delete(productMarketLambdaQueryWrapper);
        //2.1加入新价格信息
        List<ProductMarket> productMarketList = editProductDto.getProductMarketList();
        for (ProductMarket productMarket : productMarketList) {
            productMarket.setProductId(productBaseId);
            productMarketMapper.insert(productMarket);
        }
        productBaseMapper.updateById(productBase);

        //判断用户是管理人还是代理人，代理人不可修改代理人信息
        Integer manager = userProductMapper.isManager(userid, productBaseId);
        //用户信息
        Account user = selectUserById(userid);
        //用户是商品管理人或管理员
        if (user.getRoleId() == 1 || (manager != null && manager == 0)) {
            List<UserProduct> proxyUserInfoDtos = editProductDto.getProxyUserInfoDtos();
            if(proxyUserInfoDtos!=null&&proxyUserInfoDtos.size()!=0){
                for (UserProduct proxyUserInfoDto : proxyUserInfoDtos) {
                    UserProduct userProduct = new UserProduct();
                    //代理人身份
                    userProduct.setLevel(1);
                    //代理人id
                    userProduct.setUserId(proxyUserInfoDto.getUserId());
                    //代理人名称
                    userProduct.setUsername(proxyUserInfoDto.getUsername());
                    //商品id
                    userProduct.setProductId(productBaseId);
                    userProductMapper.insert(userProduct);
                }
            }

        }
        //3.操作记录表
        saveOperateRecord(editProductDto.getId(), PRODUCTSTATE.EDIT, userid);

        return RestBean.success();
    }

    /**
     * 运营小二（商品创建人或商品代理人）提交审核商品
     * @param id
     * @param userId
     * @return
     */
    @Override
    @Transactional
    public RestBean<Void> submitForReview(Long id, Long userId) {
        //找到商品
        ProductBase productBase = productBaseMapper.selectById(id);
        if (productBase == null) {
            return RestBean.failure(0, "商品不存在");
        }
        if (productBase.getState() == 2) {
            return RestBean.failure(0, "商品正在审核，请勿重复提交");
        }
        //设置状态为审核中
        productBase.setState(PRODUCTSTATE.SUBMITFORREVIEW);
        productBaseMapper.updateById(productBase);
        //操作记录表
        saveOperateRecord(id, PRODUCTSTATE.SUBMITFORREVIEW, userId);
        return RestBean.success();
    }

    @Override
    public ProductPreviewDto preview(Long id, Long userId) {
        //找到商品
        ProductInfoDto productInfoDto = selectProductInfoById(id, userId);
        ProductPreviewDto productPreviewDto = new ProductPreviewDto();
        //拷贝数据
        BeanUtils.copyProperties(productInfoDto, productPreviewDto);
        return productPreviewDto;
    }

    /**
     * 批量上线商品
     * @param ids
     * @param userId
     * @return
     */
    @Override
    @Transactional
    public RestBean<Void> batchesOnlineProduct(List<Long> ids, Long userId) {
        for (Long id : ids) {
            //找到商品
            ProductBase productBase = productBaseMapper.selectById(id);
            if (productBase == null) {
                return RestBean.failure(0, "商品不存在");
            }
            if (productBase.getState() != PRODUCTSTATE.APPROVED) {
                return RestBean.failure(0, "存在商品未审核通过");
            }
            //更新为上线
            productBase.setState(5);
            productBaseMapper.updateById(productBase);
            //更新操作记录表
            saveOperateRecord(id, PRODUCTSTATE.ONLINE, userId);

        }
        return RestBean.success();
    }

    @Override
    @Transactional
    public RestBean<Void> batchesOfflineProduct(List<Long> ids, Long userId) {
        for (Long id : ids) {
            //找到商品
            ProductBase productBase = productBaseMapper.selectById(id);
            if (productBase == null) {
                return RestBean.failure(0, "商品不存在");
            }
            if (productBase.getState() != PRODUCTSTATE.ONLINE) {
                return RestBean.failure(0, "存在商品未上线");
            }
            //更新为下线
            productBase.setState(PRODUCTSTATE.OFFLINE);
            productBaseMapper.updateById(productBase);
            //操作记录表
            saveOperateRecord(id, PRODUCTSTATE.OFFLINE, userId);
        }
        return RestBean.success();
    }

    /**
     * 管理员审核通过商品
     * @param id
     * @param userId
     * @return
     */
    @Override
    public RestBean<Void> approvedProduct(Long id, Long userId) {
        //判断是否为管理员
        Account user = selectUserById(userId);
        //不是管理员
        if (user.getRoleId() != 1) {
            return RestBean.failure(0, "没有权限");
        }
        ProductBase productBase = productBaseMapper.selectById(id);
        //获取商品状态
        Integer state = productBase.getState();
        if (productBase == null) {
            return RestBean.failure(0, "商品不存在");
        }
        if (state == PRODUCTSTATE.APPROVED) {
            return RestBean.failure(0, "商品已经审核通过，不要重复提交");
        }
        if (state != PRODUCTSTATE.SUBMITFORREVIEW) {
            return RestBean.failure(0, "商品未提交审核");
        }

        //更新为审核通过
        productBase.setState(PRODUCTSTATE.APPROVED);
        productBaseMapper.updateById(productBase);
        //操作记录表
        saveOperateRecord(id, PRODUCTSTATE.APPROVED, userId);

        return RestBean.success();
    }


    @Override
    public RestBean<Void> refuseProduct(Long id, Long userId) {
        //判断是否为管理员
        Account user = selectUserById(userId);
        //不是管理员
        if (user.getRoleId() != 1) {
            return RestBean.failure(0, "没有权限");
        }
        //找到商品
        ProductBase productBase = productBaseMapper.selectById(id);
        //获取商品状态
        Integer state = productBase.getState();
        if (productBase == null) {
            return RestBean.failure(0, "商品不存在");
        }
        if (state != PRODUCTSTATE.SUBMITFORREVIEW) {
            return RestBean.failure(0, "商品未提交审核");
        }
        //更新为审核驳回
        productBase.setState(PRODUCTSTATE.REFUSE);
        productBaseMapper.updateById(productBase);
        //操作记录表
        saveOperateRecord(id, PRODUCTSTATE.REFUSE, userId);

        return RestBean.success();
    }


}
